import base64
import os

from captcha import views as captcha_views
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from django.contrib.auth import login, logout
from rest_framework import views, generics, mixins, status
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from admin_user.authentication import AxesCaptchaAuthentication
from ztp_backend.settings import VERSION_NUM, COPYRIGHT_INFORMATION, SYSTEM_NAME, STATIC_ROOT
from .serializers import LoginSerializer, AdminUserSerializer, ResetPasswordSerializer


@api_view(['GET'])
def version(request):

    with open(os.path.join(STATIC_ROOT, "logo", "system_logo.png"), "rb") as file1:
        icon_base64 = base64.b64encode(file1.read())
        system_logo_base64 = icon_base64.decode('utf-8')
    with open(os.path.join(STATIC_ROOT, "logo", "title_logo.jpg"), "rb") as file2:
        title_icon_base64 = base64.b64encode(file2.read())
        title_logo_base64 = title_icon_base64.decode('utf-8')
    with open(os.path.join(STATIC_ROOT, "logo", "title_cn_logo.png"), "rb") as file3:
        title_cn_base64 = base64.b64encode(file3.read())
        title_cn_logo_base64 = title_cn_base64.decode('utf-8')
    data = {
        'version': VERSION_NUM,
        'system_logo': system_logo_base64,
        'title_logo': title_logo_base64,
        'title_cn_logo': title_cn_logo_base64,
        'system_name': SYSTEM_NAME,
        'copyright_information': COPYRIGHT_INFORMATION
    }
    return Response(data)


class LoginView(generics.GenericAPIView):
    """登录接口"""
    serializer_class = LoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        auth_backend = AxesCaptchaAuthentication()
        username = serializer.validated_data['username']
        password = serializer.validated_data['password']
        # print(self.request.audit)
        # if hasattr(self.request, 'audit'):
        #     self.request.audit['content'] = f'登录账号 {username}'
        print(f'登录账号 {username}, 密码{password}')
        try:
            user, _ = auth_backend.authenticate_credentials(username, password, request)
            # print(user)
            # if hasattr(self.request, 'audit'):
            #     self.request.audit['content'] = f'{user.get_admin_level_display()} {user.username} 登录系统。'

            login(request, user)
            serializer = AdminUserSerializer(instance=user)
            response = Response(serializer.data)
            return Response(serializer.data)
        except AuthenticationFailed as e:
            if getattr(request, 'axes_locked_out', None):
                # 失败次数过多，提供验证码
                captcha_key = CaptchaStore.generate_key()
                return Response({
                    'details': str(e),
                    'need_captcha': True,
                    'captcha_key': captcha_key,
                    'image_url': captcha_image_url(captcha_key),
                }, status=status.HTTP_403_FORBIDDEN)
            raise e


class LogoutView(views.APIView):
    """注销接口"""
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        # if hasattr(self.request, 'audit'):
        #     user = self.request.user
        #     self.request.audit['user'] = user
        #     self.request.audit['content'] = f'{user.get_admin_level_display()} {user.username} 登出系统。'
        user = self.request.user
        print(f'{user.username} 登出系统。')
        logout(request)
        return Response()


class UserInfoView(views.APIView):
    """返回当前用户信息"""
    permission_classes = (IsAuthenticated,)

    def get(self, request, *args, **kwargs):
        serializer = AdminUserSerializer(instance=request.user)
        return Response(serializer.data)


class ResetPasswordView(mixins.UpdateModelMixin,
                        generics.GenericAPIView):
    """重置管理员密码"""
    serializer_class = ResetPasswordSerializer
    permission_classes = (IsAuthenticated,)

    def get_object(self):
        return self.request.user

    def put(self, request, *args, **kwargs):
        res = self.update(request, *args, **kwargs)
        logout(request)
        return res

    def perform_update(self, serializer):
        if hasattr(self.request, 'audit'):
            user = self.request.user
            self.request.audit['content'] = f'{user.get_admin_level_display()} {user.username} 重置密码。'
        serializer.save()

captcha_image = api_view(['GET'])(captcha_views.captcha_image)

captcha_audio = api_view(['GET'])(captcha_views.captcha_audio)


@api_view(['GET'])
def captcha_refresh(request):
    new_key = CaptchaStore.pick()
    data = {
        'captcha_key': new_key,
        'image_url': captcha_image_url(new_key),
    }
    return Response(data)